package com.kedacom.general.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kedacom.general.feign.DeviceClient;
import com.kedacom.general.feign.rsp.UnifyData;
import com.kedacom.general.result.ResponseMessage;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件同步定时任务
 */
@Component
@Slf4j
public class GbdiTask {



    @Autowired
    DeviceClient deviceClient;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    /**
     * 同步对讲机GBID
     */
    @Scheduled(initialDelay = 10 * 1000, fixedDelay = 60 * 60 * 1000)
    public void syncDeviceGbid() {
        log.info("开始执行同步对讲机GBID定时任务");
        Map<String, Object> map = new HashMap<>(4);
        map.put("f_eq_deviceType", "PTT");
        map.put("pageSize", 1000);
        int pageNo = 0;
        long totalPages = 0;
        do {
            map.put("pageNo", pageNo);
            try {
                ResponseMessage<UnifyData<Map<String, Object>>> responseMessage = deviceClient.queryExt(map);
                log.info("统一设备对讲机信息：{}", responseMessage.toString());
                if (responseMessage.getResult() == null) {
                    break;
                }
                List<Map<String, Object>> data = responseMessage.getResult().getData();
                totalPages = responseMessage.getResult().getTotalPages();
                if (data == null || data.size() == 0) {
                    break;
                }
                for (Map<String, Object> dataMap : data) {
                    String gbid = dataMap.get("gbid") == null ? "" : dataMap.get("gbid").toString();
                    JSONObject deviceAttr= JSON.parseObject(JSON.toJSONString(dataMap.get("deviceAttr")));
                    JSONObject pttObject=deviceAttr.getJSONObject("ptt");
                    String shownNumber = pttObject.getString("shownNumber");
                    if (StringUtil.isNullOrEmpty(gbid) || StringUtil.isNullOrEmpty(shownNumber)) {
                        log.warn("设备对讲机信息:{}", dataMap);
                        continue;
                    }
                    redisTemplate.opsForHash().put("interphone_gbid_Hash", shownNumber, gbid);
                }
            } catch (Exception e) {
                log.warn("设备信息缓存异常");
                log.warn(e.getMessage());
                log.warn(e.toString());
            }
            pageNo++;
        } while (pageNo < totalPages);

        log.info("结束执行同步对讲机定时任务");
    }


}
